import * as bajaService from '@/services/bajaService';
import { TREEMENUITEM_TYPE } from '@/utils/constants';

const fetchSearchParams = async (treeMenuOrd) => {
  let searchParams = [];
  const treeMenuItem = await bajaService.Ord(treeMenuOrd);
  if(treeMenuItem) {
    const { $ordinal } = treeMenuItem.getTreeMenuItemType();
    const treeMenuItemType = TREEMENUITEM_TYPE[$ordinal];
    if(treeMenuItemType === 'SEARCH_PARAMS') {
      const navOrd = treeMenuItem.getNavOrd().toString();
      const searchParamRoot = await bajaService.Ord(navOrd+'/searchParamRoot');
      if(searchParamRoot) {
        searchParams = await bajaService.fetchNavChildren(searchParamRoot);
        if(searchParams) {
          for(let i=0; i<searchParams.length; i++) {
            const { $typeSpec } = searchParams[i].getType();
            if($typeSpec === 'ibmsSupervisor:SearchParamGroup') {
              const searchParamItems = await bajaService.fetchNavChildren(searchParams[i]);
              searchParams[i] = {
                title: searchParams[i].getTitle(),
                value: searchParams[i].$handle,
                key: searchParams[i].$handle
              }
              if(searchParamItems) {
                searchParams[i].children = searchParamItems.map((item)=>{
                  return ({
                    title: item.getTitle(),
                    value: item.$handle,
                    key: item.$handle,
                    historyOrd: item.getHistoryOrd().$ord,
                    alarmClassOrd: item.getAlarmClassOrd().$ord
                  })
                });
              }
            } else if($typeSpec === 'ibmsSupervisor:SearchParamItem') {
              searchParams[i] = {
                title: searchParams[i].getTitle(),
                value: searchParams[i].$handle,
                key: searchParams[i].$handle,
                historyOrd: searchParams[i].getHistoryOrd().$ord,
                alarmClassOrd: searchParams[i].getAlarmClassOrd().$ord
              }
            }
          }
        } else {
          searchParams = []
        }
      }
    }
  }
  return searchParams;
  // return Promise.resolve(searchParams);
}

export { fetchSearchParams };
